import type { Router } from "express"
import type { Ioracle, IcallbackFn } from "../../types"
import multer from "multer"
import { logger } from "../../utils"
import fs from "fs"


const storage = multer.diskStorage({
  //上传文件到服务器的存储位置
  destination: '../uploadFile/resume_manage',
  filename: function (req, file, callback) {
    //上传的文件信息
    let type:string = (typeof(req))
    type = type + "tempSource"
    // 用來獲取後綴名
    var fileFormat = (file.originalname).split('.')
    // 获取时间戳
    var filename = new Date().getTime()
    // 文件的命名为：时间戳 + 文件附件名 + 文件的后缀名
    callback(null, filename + "-tempname"  + "." + fileFormat[fileFormat.length-1])
  }
})
const upload = multer({
  storage:storage
})


export default (router: Router, oracle: Ioracle, callbackFn: IcallbackFn) => {
  router.post("/getResumeData", (_req, res) => {
    let sql = " select a.id,a.sex,a.age,a.school,a.profession,a.degree "
    sql += " ,to_char(a.graduate_date,'yyyymmdd') graduate_date "
    sql += " ,a.salary_k,a.salary_m,a.salary_w,a.recommend_job "
    sql += " ,a.emergency_level,a.source,a.interview_state,a.chinese_name "
    sql += " ,b.chinese_name created_by "
    sql += " ,to_char(a.created_date,'yyyymmdd') created_date "
    sql += " ,to_char(a.recommend_date,'yyyy-mm-dd') recommend_date,a.recommend_org,a.recommend_dept "
    sql += " ,a.recommend_state,to_char(a.check_date1,'yyyy-mm-dd') check_date1 "
    sql += " ,to_char(a.check_date2,'yyyy-mm-dd') check_date2,to_char(a.check_date3,'yyyy-mm-dd') check_date3 "
    sql += " ,a.check_state1,a.check_state2,a.check_state3,a.salary_state "
    sql += " ,to_char(last_updated_date,'yyyy-mm-dd') last_updated_date,a.appendix_url,a.check_state4,to_char(a.abadon_review_date,'yyyy-mm-dd')abadon_review_date "
    sql += " from xx_resume_manage_header a,user_info_n b "
    sql += " where a.created_by = b.account "
    callbackFn(res, oracle.connHrTest, { sql })
  })

  router.post("/insertResumeData", (req, res) => {
    const { chinese_name, sex, age, school } = req.body
    const { profession, degree, graduate_date } = req.body
    const { salary_k, salary_m, salary_w, recommend_job } = req.body
    const { emergency_level, source, interview_state, remarks } = req.body
    const { recommend_date, recommend_org, recommend_dept } = req.body
    const { recommend_state, check_date1, check_date2, check_date3, abadon_review_date } = req.body
    const { check_state1, check_state2, check_state3, salary_state, check_state4 } = req.body
    //let sql = " declare "
    //sql += " v_id varchar2(20); "
    //sql += " begin "
    //sql += " select to_char(sysdate,'yyyymmddhh24miss') into v_id from dual; "
    let sql = " insert into xx_resume_manage_header "
    sql += " (id,chinese_name,sex,age,school "
    sql += " ,profession,degree,graduate_date "
    sql += " ,salary_k,salary_m,salary_w,recommend_job "
    sql += " ,emergency_level,source,interview_state "
    sql += " ,created_date,created_by,remarks "
    sql += " ,recommend_date,recommend_org,recommend_dept "
    sql += " ,recommend_state,check_date1,check_date2,check_date3 "
    sql += " ,check_state1,check_state2,check_state3,salary_state,last_updated_date,check_state4,abadon_review_date) "
    sql += ` values(to_char(sysdate,'yyyymmddhh24miss'),'${chinese_name}','${sex}','${age}','${school}' `
    sql += ` ,'${profession}','${degree}',to_date('${graduate_date}','yyyy-mm-dd') `
    sql += ` ,'${salary_k}','${salary_m}','${salary_w}','${recommend_job}' `
    sql += ` ,'${emergency_level}','${source}','${interview_state}' `
    sql += ` ,sysdate,'xdomain\\yufangwei','${remarks}' `
    sql += ` ,to_date('${recommend_date}','yyyy-mm-dd'),'${recommend_org}','${recommend_dept}','${recommend_state}' `
    sql += ` ,to_date('${check_date1}','yyyy-mm-dd'),to_date('${check_date2}','yyyy-mm-dd'),to_date('${check_date3}','yyyy-mm-dd') `
    sql += ` ,'${check_state1}','${check_state2}','${check_state3}','${salary_state}',sysdate,'${check_state4}',to_date('${abadon_review_date}','yyyy-mm-dd')) `
    // sql += " insert into xx_resume_manage_line "
    // sql += " (id,interview_state,attr1,attr2,attr3 "
    // sql += " ,check_date,created_date,created_by "
    // sql += " ,check_date1,check_date2) "
    // sql += ` values(v_id,'${interview_state}','${attr1}','${attr2}','${attr3}' `
    // sql += ` ,to_date('${check_date}','yyyy-mm-dd'),sysdate,'' `
    // sql += ` ,to_date('${check_date1}','yyyy-mm-dd'),to_date('${check_date2}','yyyy-mm-dd')) `
    // sql += " end; "
    callbackFn(res, oracle.connHrTest, { sql })
  })

  router.post("/modifyResumeData", (req,res) => {
    const { id } = req.body
    const { chinese_name, sex, age, school } = req.body
    const { profession, degree, graduate_date } = req.body
    const { salary_k, salary_m, salary_w, recommend_job } = req.body
    const { emergency_level, source, interview_state, remarks } = req.body
    const { recommend_date, recommend_org, recommend_dept } = req.body
    const { recommend_state, check_date1, check_date2, check_date3, abadon_review_date } = req.body
    const { check_state1, check_state2, check_state3, salary_state, check_state4 } = req.body
    let sql = " update xx_resume_manage_header "
    sql += ` set chinese_name = '${chinese_name}',sex='${sex}' `
    sql += ` ,age = '${age}',school = '${school}',profession = '${profession}' `
    sql += ` ,degree = '${degree}',graduate_date = to_date('${graduate_date}','yyyy-mm-dd') `
    sql += ` ,salary_k = '${salary_k}',salary_m = '${salary_m}',salary_w='${salary_w}' `
    sql += ` ,recommend_job='${recommend_job}',emergency_level='${emergency_level}' `
    sql += ` ,source='${source}',interview_state='${interview_state}',remarks='${remarks}' `
    sql += ` ,recommend_date=to_date('${recommend_date}','yyyy-mm-dd') `
    sql += ` ,recommend_org = '${recommend_org}',recommend_dept='${recommend_dept}' `
    sql += ` ,recommend_state='${recommend_state}',check_date1=to_date('${check_date1}','yyyy-mm-dd') `
    sql += ` ,check_date2=to_date('${check_date2}','yyyy-mm-dd'),check_date3=to_date('${check_date3}','yyyy-mm-dd') `
    sql += ` ,check_state1='${check_state1}',check_state2='${check_state2}',check_state4='${check_state4}' `
    sql += ` ,check_state3='${check_state3}',salary_state='${salary_state}',abadon_review_date=to_date('${abadon_review_date}','yyyy-mm-dd') `
    sql += " ,last_updated_date = sysdate "
    sql += ` where id = '${id}' `
    callbackFn(res, oracle.connHrTest, { sql })
  })

  router.post("/uploadFile", upload.single("file"),(req,res)=>{
    const {id,filename} = req.body
    if (filename && req.file?.filename) {
      //根據文件命名規則，文件被命名成了 時間戳 + -tempname + 後綴名的形式，這裏將tempname替換成為原始的文件
      //傳過來的文件名，只有文件名，不帶後綴
      let filenameOnlyName = filename.split('.')[filename.split('.').length-2]
      let newfileName = req.file?.filename.replace("tempname",filenameOnlyName)
      fs.renameSync("G:\\uploadFile\\resume_manage\\"+req.file?.filename.toString(),"G:\\uploadFile\\resume_manage\\"+ newfileName)
      let sql = ` update xx_resume_manage_header set appendix_url ='${newfileName}'`
      sql += ` where id='${id}'`
      oracle
        .connHrTest({ sql })
        .then(() => {
          logger.info("附件上传OK!")
          res.send({ code: 200, message: "success", data: newfileName })
        })
        .catch((err) => {
          logger.error("數據庫更新附件失敗!" + err)
          res.send({ code: 0, message: err })
        })
    } else {
      logger.error("無需附件上傳!")
      res.send({code:200,message:'上傳成功'})
    }
  })

  //下载附件
  router.post('/download', (req,res) => {
    const {filename} = req.body
    const filePath = '../uploadFile/resume_manage/' + filename
    const f = fs.createReadStream(filePath);
    res.writeHead(200, {
      //'Content-Type': 'application/force-download',
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename=' + filename.split('-')[filename.split('-').length-1],
      'Access-Control-Expose-Headers': 'Content-Disposition',//核心配置
    });
    f.pipe(res);
    //console.log(res)
    //res.download(filePath)
  })

  return router
}
